<template>
	<view class="wrapper">
		<view>
			<u-navbar :is-back="true" :border-bottom="false" :customBack="backFn"></u-navbar>
			<view>
				<image class="flex mx-auto" src="/static/logo.png" mode="aspectFill" style="width: 200rpx;height: 200rpx;">
				</image>
				<view class="title text-center">工匠租</view>
				<!-- <view class="desc text-center">
					欢迎登录
				</view> -->
			</view>
			<!-- 手机号 -->
			<!--#ifdef H5-->
			<view v-show="!enableUserPwdBox">
				<view class="mobile">
					<input class="w-100" :placeholderStyle="placeholderStyle" placeholder="请输入手机号" focus v-model="codeData.mobile"
						type="number" maxlength="11" />
				</view>

				<view class="position-relative flex align-center mobile">
					<input class="w-100" :placeholderStyle="placeholderStyle" placeholder="请输入验证码" v-model.trim="codeData.code">
					</input>
					<view class="position-absolute top-0 right-0 mr-2 fs-28" style="margin-top:10px;">
						<u-verification-code change-text="xs" end-text="重新获取" unique-key="page-login" :seconds="seconds" @end="end"
							@start="start" ref="uCode" @change="codeChange">
						</u-verification-code>
						<span @tap="fetchCode" :style="{ color: codeColor }">
							{{ tips }}</span>
					</view>
				</view>

				<view :class="!enableCodeBtnColor || !enablePrivacy ? 'disable' : 'fetch'" class="btn" @click="submit">
					登录
				</view>
			</view>
			<!--#endif-->


			<!--#ifdef MP-WEIXIN-->
			<view style="padding:200rpx 0 100rpx;">
				<button @tap="getOpenId(true)" class="wx-login-btn">
					一键登录
				</button>
			</view>
			<!--#endif-->
			<!--#ifdef MP-ALIPAY-->
			<view style="padding:100rpx 0;">
				<button @tap="getAuthCodeSilently(true)" class="alipay-login-btn">
					一键登录
				</button>
			</view>
			<!--#endif-->

			<view class="flex align-center justify-center mt-2">
				<radio-group @change="radioChange">
					<radio value="1" :checked="enablePrivacy" activeBackgroundColor="#e87722" style="transform:scale(0.7)" />
				</radio-group>

				<view class="tips">已阅读并同意<text @click="navigateToPrivacy('PRIVACY_POLICY')">《隐私协议》</text> 与
					<text @click="navigateToPrivacy('USER_AGREEMENT')">
						《用户协议》
					</text>
				</view>
			</view>

		</view>

		<u-modal :confirm-color="lightColor" v-model="agreementShow" title="温馨提示" cancel-text="不同意" confirm-text="同意"
			:show-cancel-button="true" @confirm="agreementFn(true,'confirm')">
			<view class="tips text-center my-3">已阅读并同意<text @click="navigateToPrivacy('PRIVACY_POLICY')">《隐私协议》</text> 与
				<text @click="navigateToPrivacy('USER_AGREEMENT')">
					《用户协议》
				</text>
			</view>
		</u-modal>


		<u-modal v-model="bindPhoneShow" title="授权登录" class="position-relative login-modal" :show-confirm-button="false"
			:show-cancel-button="false">
			<view class="slot-content p-2">
				<!-- <uni-icons class="position-absolute top-0 right-0 mt-1 mr-1" type="closeempty" size="20" color="#000"
					@tap="bindPhoneShow = false"></uni-icons> -->
				<view class="fs-32 font-weight-bold">获取以下权限为您提供服务</view>
				<view class="bgf7f7f7 p-2 my-2 fs-28">
					<view class="mb-2">1、获取你的手机号提供更好的账户安全，物流，订单状态提醒等服务（在接下来授权手机号的弹窗中选择“允许”）</view>
					<view>2、使用我们的相关服务，需要将您的手机号授权给我们。</view>
				</view>
				<!--#ifdef MP-WEIXIN-->
				<button open-type="getPhoneNumber" scope="phoneNumber" @getphonenumber="wxGetPhoneNumber" class="wx-login-btn">
					点击授权
				</button>
				<!--#endif-->

				<!--#ifdef MP-ALIPAY-->
				<button open-type="getAuthorize" scope="phoneNumber" @click="onGetPhoneNumber" class="alipay-login-btn">
					点击授权
				</button>
				<!--#endif-->
			</view>
		</u-modal>
	</view>
</template>

<script>
	import api from "@/config/api.js";
	import {
		sendMobile,
		smsLogin,
		userLogin,
		logout,
		getWechatOpenId,
		getAlipayUserId,
		alipayLogin,
		alipayBindPhone,
		wechatLogin,
		wechatBindPhone
	} from "@/api/login";
	import {
		getUserInfo
	} from "@/api/members";
	import {
		whetherNavigate
	} from "@/utils/Foundation"; //登录跳转
	import storage from "@/utils/storage.js"; //缓存
	import {
		md5
	} from "@/utils/md5.js";

	export default {

		data() {
			return {
				flage: false, //是否验证码验证
				codeFlag: true, //验证开关，用于是否展示验证码
				tips: "",
				enableUserPwdBox: false, //帐号密码登录
				current: 0,
				codeColor: "#999", //按钮验证码颜色
				lightColor: this.$lightColor,
				seconds: 60, //默认验证码等待时间
				userData: {
					username: "",
					password: "",
				},
				codeData: {
					mobile: "", //手机号
					code: "", //验证码
				},
				showBack: false,
				enableUserBtnColor: false,
				enablePrivacy: false, //隐私政策
				enableCodeBtnColor: false,
				placeholderStyle: "font-size: 28rpx;line-height: 32rpx;color: #999999;",
				isLoading: false, // 防止重复提交
				bindPhoneShow: false,
				agreementShow: false
			};
		},
		onShow() {
			storage.setAccessToken("");
			storage.setRefreshToken("");
			storage.setUserInfo({});
		},
		watch: {
			current(val) {
				val ? (this.showBack = true) : (this.showBack = false);
			},
			userData: {
				handler(val) {
					if (this.userData.username && this.userData.password) {
						this.enableUserBtnColor = true;
					} else {
						this.enableUserBtnColor = false;
					}
				},
				deep: true,

			},
			codeData: {
				handler(val) {
					if (this.codeData.mobile && this.codeData.code) {
						this.enableCodeBtnColor = true;
					} else {
						this.enableCodeBtnColor = false;
					}
				},
				deep: true,
			}

		},
		methods: {
			backFn() {
				uni.reLaunch({
					url: '/pages/tabbar/home/home'
				})
			},
			agreementFn(flag, type) {
				//#ifdef MP-WEIXIN
				this.getOpenId(flag, null, type)
				//#endif

				//#ifdef MP-ALIPAY
				this.getAuthCodeSilently(flag, null, type)
				//#endif
			},
			radioChange(e) {
				this.enablePrivacy = true
			},
			wxGetPhoneNumber(e) {
				const {
					encryptedData,
					iv,
					code
				} = e.detail
				this.getOpenId(encryptedData, iv)
			},
			wechatLogin(code, encryptedData, iv) {
				wechatLogin({
					code
				}).then(res => {
					if (res.code == 1) {
						if (res.data.is_new) {
							this.bindPhoneShow = true
						} else {
							const data = res.data
							if (data) {
								storage.setAccessToken(data.userInfo.token);
								/**
								 * 个人信息存储到缓存userInfo中
								 */
								storage.setUserInfo(data.userInfo);
								storage.setHasLogin(true);
								storage.setAutoCp(0)
								// 登录成功
								uni.showToast({
									title: "提示",
									content: "登录成功!",
									icon: "none",
								});
								whetherNavigate();
							}
						}
					}
				}).finally(() => {
					uni.hideLoading()
				})
			},
			wechatBindPhone(code, encryptedData, iv) {
				wechatBindPhone({
					code,
					encrypted_data: encryptedData,
					iv
				}).then(res => {
					const data = res.data
					if (data) {
						storage.setAccessToken(data.userInfo.token);
						/**
						 * 个人信息存储到缓存userInfo中
						 */
						storage.setUserInfo(data.userInfo);
						storage.setHasLogin(true);
						storage.setAutoCp(0)
						// 登录成功
						uni.showToast({
							title: "提示",
							content: "登录成功!",
							icon: "none",
						});
						whetherNavigate();
					}
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 手机号授权回调
			onGetPhoneNumber() {
				if (this.isLoading) return;
				this.isLoading = true;
				// 1. 判断用户是否授权
				const _this = this
				my.getPhoneNumber({
					success: (res) => {
						let {
							response,
							sign
						} = JSON.parse(res.response);
						_this.getAuthCodeSilently(response, sign);
						_this.isLoading = false;
						uni.hideLoading()
					},
					fail: (res) => {
						console.log('res-----', res)
						_this.isLoading = false;
						uni.showToast({
							title: '请允许获取手机号以完成登录',
							icon: 'none'
						})
					},
				});
			},
			codeChange(text) {
				this.tips = text;
			},
			getOpenId(encryptedData, iv, type) {
				if (type == 'confirm') {
					this.enablePrivacy = true
				}
				if (!this.enablePrivacy) {
					this.agreementShow = true
					return;
				}
				uni.showLoading()
				const _this = this
				uni.login({
					provider: 'weixin',
					scopes: "auth_base",
					success: function(loginRes) {
						console.log('loginRes-----', loginRes.code);
						if (encryptedData && !iv) {
							_this.wechatLogin(loginRes.code)
						} else if (iv) {
							_this.wechatBindPhone(loginRes.code, encryptedData, iv)
						}
					},
					complete(e) {
						//获取用户信息
						uni.getUserInfo({
							provider: 'weixin',
							success: function(infoRes) {
								//写入用户信息
								uni.setStorageSync("nickname", infoRes.userInfo.nickName);
								uni.setStorageSync("avatar", infoRes.userInfo.avatarUrl);
								uni.setStorageSync("unionId", infoRes.userInfo.unionId || infoRes.userInfo.unionid);
							},
						});
					},
				});
			},
			getWechatOpenId(code) {
				getWechatOpenId({
					code
				}).then(res => {
					uni.setStorageSync('openId', res.data.openid);
					whetherNavigate();
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 静默授权获取 authCode
			getAuthCodeSilently(encryptedData, iv, type) {
				if (type == 'confirm') {
					this.enablePrivacy = true
				}
				if (!this.enablePrivacy) {
					this.agreementShow = true
					return;
				}
				const _this = this
				my.getAuthCode({
					scopes: 'auth_base', // 静默授权（基础权限，无弹窗）
					success: (res) => {
						if (res.authCode) {
							console.log('静默授权成功，authCode：', res.authCode);
							// 发送 authCode 到后端换取 userId
							// 手机号登录
							if (encryptedData && !iv) {
								_this.alipayLogin(res.authCode, encryptedData, iv)
							} else if (iv) {
								this.alipayBindPhone(res.authCode, encryptedData, iv)
							}
						}
					},
					fail: (err) => {
						console.error('静默授权失败：', err);
					}
				});
			},
			// 发送 authCode 到后端，换取 userId
			getUserIdByCode(code) {
				getAlipayUserId({
					authCode: code
				}).then(res => {
					uni.setStorageSync('openId', res.data.user_id);
					whetherNavigate();
				}).finally(() => {
					uni.hideLoading()
				})
			},
			alipayLogin(code, encryptedData, iv) {
				alipayLogin({
					auth_code: code
				}).then(res => {
					if (res.code == 1) {
						if (res.data.is_new) {
							this.bindPhoneShow = true
						} else {
							const data = res.data
							if (data) {
								storage.setAccessToken(data.userInfo.token);
								/**
								 * 个人信息存储到缓存userInfo中
								 */
								storage.setUserInfo(data.userInfo);
								storage.setHasLogin(true);
								storage.setAutoCp(0)
								const toUrl = uni.getStorageSync('toPay')
								if (toUrl) {
									uni.redirectTo({
										url: toUrl
									})
								} else {
									// 登录成功
									uni.showToast({
										title: "提示",
										content: "登录成功!",
										icon: "none",
									});
									whetherNavigate();
								}
							}
						}
					}
				}).finally(() => {
					uni.hideLoading()
				})
			},
			alipayBindPhone(code, encryptedData, iv) {
				alipayBindPhone({
					auth_code: code,
					response: encryptedData,
					sign: iv
				}).then(res => {
					console.log('alipayBindPhone-----', res)
					const data = res.data
					if (data) {
						storage.setAccessToken(data.userInfo.token);
						/**
						 * 个人信息存储到缓存userInfo中
						 */
						storage.setUserInfo(data.userInfo);
						storage.setHasLogin(true);
						storage.setAutoCp(0)
						const toUrl = uni.getStorageSync('toPay')
						if (toUrl) {
							uni.redirectTo({
								url: toUrl
							})
						} else {
							// 登录成功
							uni.showToast({
								title: "提示",
								content: "登录成功!",
								icon: "none",
							});
							whetherNavigate();
						}
					}
				}).finally(() => {
					uni.hideLoading()
				})
			},
			// 提交
			submit() {
				if (!this.enableCodeBtnColor) return;
				/**
				 * 清空当前账号信息
				 */
				storage.setHasLogin(false);
				storage.setAccessToken("");
				storage.setRefreshToken("");
				storage.setUserInfo({});
				/**
				 * 执行登录
				 */
				smsLogin({
					mobile: this.codeData.mobile,
					captcha: this.codeData.code,
					type: 'user_register'
				}).then(
					(res) => {
						console.log(res)
						const data = res.data
						if (data) {
							storage.setAccessToken(data.userInfo.token);
							/**
							 * 个人信息存储到缓存userInfo中
							 */
							storage.setUserInfo(data.userInfo);
							storage.setHasLogin(true);
							storage.setAutoCp(0)
							// 登录成功
							uni.showToast({
								title: res.msg,
								icon: "none",
							});
							//#ifdef MP-WEIXIN
							this.getOpenId()
							// #endif

							//#ifdef MP-ALIPAY
							this.getAuthCodeSilently()
							// #endif
							// #ifdef H5
							const prepage_url = uni.getStorageSync('prepage_url')
							if (prepage_url) {
								uni.removeStorageSync('prepage_url')
								console.log('prepage_url----', prepage_url)
								uni.redirectTo({
									url: prepage_url
								})
								return;
							}
							uni.switchTab({
								url: "/pages/tabbar/home/home",
							});
							// #endif
						}
					}
				);
			},
			// 跳转
			navigateToPrivacy(val) {
				uni.navigateTo({
					url: "/pages/navigation/webview?type=" + val,
				});
			},

			// 点击获取验证码
			start() {
				this.codeColor = "#999";
				this.$u.toast("验证码已发送");
				this.flage = false;
			},
			/**点击验证码*/
			codeChange(text) {
				this.tips = text;
			},
			/** 结束验证码后执行 */
			end() {
				this.codeColor = this.lightColor;
			},
			// 发送验证码
			async fetchCode() {
				if (!this.enablePrivacy) {
					uni.showToast({
						title: "请同意用户隐私",
						duration: 2000,
						icon: "none",
					});
					return false;
				}

				if (!this.$u.test.mobile(this.codeData.mobile)) {
					uni.showToast({
						title: "请填写正确手机号",
						duration: 2000,
						icon: "none",
					});
					return false;
				}
				// 向后端请求验证码
				uni.showLoading({});
				let res = await sendMobile({
					mobile: this.codeData.mobile,
					template_code: 'user_login_register'
				});
				uni.hideLoading()
				if (res.code == 1) {
					this.current = 1;
					this.$refs.uCode.start();
				} else {
					uni.showToast({
						title: res.msg,
						duration: 2000,
						icon: "none",
					});
				}
			},
		},
	};
</script>
<style>
	page {
		background: #fff;
	}
</style>
<style lang="scss" scoped>
	.wrapper {
		padding: 0 40rpx;
	}

	.title {
		padding-top: calc(104rpx);
		font-style: normal;
		line-height: 1;
		font-weight: 500;
		font-size: 56rpx;
		color: #333;
	}

	.box-code {
		margin-top: 78rpx;
	}

	.desc,
	.desc-light {
		font-size: 32rpx;
		line-height: 32rpx;
		color: #333333;
		margin-top: 40rpx;
	}

	.desc {
		color: #333;
	}

	.desc-light {
		color: #999999;

		>span {
			color: #333;
			margin-left: 8rpx;
		}
	}

	.mobile {
		margin-top: 80rpx;
	}

	.disable {
		background: linear-gradient(90deg, #ffdcba 2.21%, #ffcfb2 99.86%);
	}

	.fetch {
		background: linear-gradient(57.72deg, #ff8a19 18.14%, #e87722 98.44%);
	}

	.btn {
		border-radius: 100px;
		width: 590rpx;
		height: 80rpx;
		font-size: 30rpx;
		line-height: 80rpx;
		text-align: center;
		color: #ffffff;
		margin: 100rpx auto 0;
	}

	.tips {
		font-size: 12px;
		line-height: 20px;
		width: 546rpx;

		>text {
			color: $light-color;
		}
	}

	.fetch-btn {
		width: 370rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background: #f2f2f2;
		border-radius: 100rpx;
		font-size: 28rpx;
		color: #999;

		margin: 71rpx auto 0 auto;
	}

	.login-list {
		display: flex;
		width: 590rpx;
		position: absolute;
		top: 1200rpx;
		align-items: center;
		justify-content: center;
	}

	.login-item {
		width: 80rpx;
		border-radius: 10rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		margin: 0 20rpx;
	}

	.user-password-tips {
		text-align: center;
		color: $main-color;
		margin: 20px 0;
	}

	.wx-login-btn {
		width: 60%;
		background-color: #07c160;
		color: #fff;
		border-radius: 50px;
		border: 0;
		font-size: 28rpx;
	}

	.alipay-login-btn {
		width: 60%;
		background-color: #1677ff;
		color: #fff;
		border-radius: 50px;
		border: 0;
		font-size: 28rpx;
		margin: 0 auto;
	}
</style>